package org.springframework.fusion.elasticsearch.demo;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import org.springframework.fusion.elasticsearch.domain.Text;
import org.springframework.fusion.elasticsearch.utlis.JsonUtils;

@SuppressWarnings("all")
public class ElasticSearch {

	// 1、创建es客户端连接对象
	static TransportClient client = null;
	static {
		try {
			client = new PreBuiltTransportClient(Settings.EMPTY)
					.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.2.217"), 9300));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void base(SearchResponse searchResponse) {
		// 3、遍历搜索结果数据
		SearchHits hits = searchResponse.getHits();
		// 获取命中次数，查询结果有多少对象
		System.out.println("查询结果有：" + hits.getTotalHits() + "条");
		Iterator<SearchHit> iterator = hits.iterator();
		while (iterator.hasNext()) {
			SearchHit searchHit = iterator.next();
			// 每个查询对象
			System.out.println(searchHit.getSourceAsString());
			// 获取字符串格式打印
			System.out.println("title:" + searchHit.getSourceAsMap().get("title"));
		}
		client.close();
	}

	// 创建索引
	public static void test1() throws Exception {
		long time = new Date().getTime();
		// 2、创建文档内容
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", time)
				.field("title", "elasticsearch是一个基于lucene的搜索服务").field("content", "中华人民共和国").endObject();
		// 3、建立文档对象
		client.prepareIndex("blog2", "article", String.valueOf(time)).setSource(builder).get();
		client.close();
	}

	// 查询全部
	public static void test2() throws Exception {
		// 2、设置搜索条件
		SearchResponse searchResponse = client.prepareSearch("blog1").setTypes("article")
				.setQuery(QueryBuilders.matchAllQuery()).get();
		base(searchResponse);
	}

	// 字符串查询
	public static void test3() throws Exception {
		// 2、设置搜索条件
		SearchResponse searchResponse = client.prepareSearch("blog1").setTypes("article")
				.setQuery(QueryBuilders.queryStringQuery("共和国")).get();
		client.prepareSearch("blog1").setTypes("article").setQuery(QueryBuilders.commonTermsQuery("content", "共和国"))
				.get();
		base(searchResponse);

	}

	// 词条查询
	public static void test4() throws Exception {
		// 2、设置搜索条件
		SearchResponse searchResponse = client.prepareSearch("blog1").setTypes("article")
				.setQuery(QueryBuilders.termQuery("content", "中")).get();
		base(searchResponse);

	}

	// 词条查询
	public static void test5() throws Exception {
		// 2、设置搜索条件
		SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
				.setQuery(QueryBuilders.wildcardQuery("content", "中华")).get();
		base(searchResponse);

	}

	// 删除索引
	public static void test6() throws Exception {
		client.admin().indices().prepareDelete("blog2").get();
		client.close();
	}

	// 删除数据
	public static void test7() throws Exception {
		// client.prepareDelete("blog1", "article", "1558872732005").get();
		client.delete(new DeleteRequest("blog1", "article", "1")).get();
		client.close();
	}

	// 创建映射
	public static void test8() throws Exception {
		client.admin().indices().prepareCreate("blog2").get();
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article")
				.startObject("properties").startObject("id").field("type", "long").field("store", "yes").endObject()
				.startObject("title").field("type", "string").field("store", "yes").field("analyzer", "ik_max_word")
				.endObject().startObject("content").field("type", "string").field("store", "yes")
				.field("analyzer", "ik_max_word").endObject().endObject().endObject().endObject();
		PutMappingRequest mapping = Requests.putMappingRequest("blog2").type("article").source(builder);
		client.admin().indices().putMapping(mapping).get();
		client.close();
	}

	// 对象创建文档
	public static void test9() throws Exception {
		Text article = new Text();
		article.setId(new Date().getTime());
		article.setTitle("搜索工作其实很快乐");
		article.setContent(
				"我们希望我们的搜索解决方案要快，我们希望有一个零配置和一个完全免费的搜索模 式，我们希望能够简单地使用JSON通过HTTP的索引数据，我们希望我们的搜索服务器始终可用，我们希望能够一台开 始并扩展到数百，我们要实时搜索，我们要简单的多租户，我们希望建立一个云的解决方案。Elasticsearch旨在解 决所有这些问题和更多的问题。");
		String objectToJson = JsonUtils.ObjectToJson(article);
		client.prepareIndex("blog2", "article", article.getId().toString()).setSource(objectToJson).get();
		client.close();

	}

	// 修改文档
	public static void test10() throws Exception {
		Text article = new Text();
		article.setId(1558874420832L);
		article.setTitle("搜索工作其实很快乐--修改文档3");
		article.setContent(
				"我们希望我们的搜索解决方案要快，我们希望有一个零配置和一个完全免费的搜索模 式，我们希望能够简单地使用JSON通过HTTP的索引数据，我们希望我们的搜索服务器始终可用，我们希望能够一台开 始并扩展到数百，我们要实时搜索，我们要简单的多租户，我们希望建立一个云的解决方案。Elasticsearch旨在解 决所有这些问题和更多的问题。");
		String objectToJson = JsonUtils.ObjectToJson(article);
		// 第一种方式
		// client.prepareIndex("blog2", "article",
		// article.getId().toString()).setSource(objectToJson).get();
		// 第二种方式
		// client.prepareUpdate("blog2", "article",
		// article.getId().toString()).setDoc(objectToJson).get();
		// 第三种方式
		client.update(new UpdateRequest("blog2", "article", article.getId().toString()).doc(objectToJson)).get();
		client.close();
	}

	// 分页查询
	public static void test11() throws Exception {
		// 默认每页10条记录
		SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog2").setTypes("article")
				.setQuery(QueryBuilders.matchAllQuery());
		// setFrom()：从第几条开始检索，默认是0。
		// setSize():每页最多显示的记录数。
		searchRequestBuilder.setFrom(0).setSize(20);
		// 排序
		searchRequestBuilder.addSort("id", SortOrder.DESC);
		SearchResponse searchResponse = searchRequestBuilder.get();
		base(searchResponse);
	}

	// 高亮
	public static void test12() throws Exception {
		SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog2").setTypes("article")
				.setQuery(QueryBuilders.termQuery("content", "中华"));
		HighlightBuilder hiBuilder = new HighlightBuilder();
		hiBuilder.preTags("<font style='color:red'>");
		hiBuilder.postTags("</font>");
		hiBuilder.field("content");
		searchRequestBuilder.highlighter(hiBuilder);
		// 获得查询结果数据
		SearchResponse searchResponse = searchRequestBuilder.get();
		SearchHits searchHits = searchResponse.getHits();
		System.out.println("共搜到:" + searchHits.getTotalHits() + "条结果!");
		for (SearchHit hit : searchHits) {
			System.out.println(hit.getSourceAsString());
			org.elasticsearch.common.text.Text[] text = hit.getHighlightFields().get("content").getFragments();
			for (org.elasticsearch.common.text.Text str : text) {
				System.out.println(str);
			}
		}

	}

	public static void main(String[] args) throws Exception {
		test12();
	}
}
